/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean.Warehouse;

import entity.Address;
import entity.RawMaterial;
import entity.Supplier;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import managedbean.UserSessionManagerBean;

import session.stateless.SupplierSessionBeanLocal;
import session.stateless.ProductSessionBeanLocal;
import session.stateless.LogSessionBeanLocal;

@ManagedBean(name = "supplierManagerBean")
@RequestScoped
public class SupplierManagerBean implements Serializable {

    @EJB
    private SupplierSessionBeanLocal supplierSessionBeanLocal;
    @EJB
    private ProductSessionBeanLocal productSessionBeanLocal;
    @EJB
    private LogSessionBeanLocal logSessionBeanLocal;
    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    private String loadAddSupplier;
    private String loadManageSuppliers;
    private String loadUpdateSupplier;
    private Supplier selectedSupplier;
    private RawMaterial selectedSellingRawMaterial;
    private String supplierId;
    private String name;
    private Integer contact;
    private Address supplierAddress;
    private RawMaterial rawMaterial = new RawMaterial();
    private String street;
    private String country;
    private String city;
    private Integer postal;
    private String ranking;		//Poor, Moderate, Reliable
    private String comment;
    private List<RawMaterial> rawMaterialsList = new ArrayList<RawMaterial>();
    private List<RawMaterial> rawMaterialsSelling = new ArrayList<RawMaterial>();
    private String email;
    private String company;
    private List<Supplier> suppliers = new ArrayList<Supplier>();

    public void removeSupplier(ActionEvent event) {
        try {
            if (selectedSupplier != null) {
                supplierSessionBeanLocal.deleteSupplier(selectedSupplier.getSupplierId());

                logSessionBeanLocal.addLog("Delete Supplier", "Supplier Deleted: " + company, "searchSupplier.xhtml", userSessionManagerBean.getUserId());

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/searchSuppliers.xhtml"); //redirect to searchSuppliers.xhtml
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a supplier before continuing.", ""));
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void deleteSupplierRawMaterial(ActionEvent event) {
        try {
            if (selectedSellingRawMaterial != null) {
                System.out.println("SelectedRawMaterial: " + selectedSellingRawMaterial.getName());
                supplierSessionBeanLocal.deleteSupplierRawMaterial(selectedSupplier.getSupplierId(), selectedSellingRawMaterial.getId());

                logSessionBeanLocal.addLog("Update Supplier", "Delete Raw Material From Supplier: " + company, "updateSupplier.xhtml", userSessionManagerBean.getUserId());

                selectedSupplier = supplierSessionBeanLocal.getSupplierBySupId(selectedSupplier.getSupplierId());
                selectedSupplier.setName(name);
                selectedSupplier.setContact(contact);
                selectedSupplier.setCompany(company);
                selectedSupplier.setEmail(email);
                selectedSupplier.setRanking(ranking);
                selectedSupplier.setComment(comment);
                selectedSupplier.setSupplierAddress(supplierAddress);
                selectedSupplier.setSupplierId(supplierId);

                userSessionManagerBean.setSelectedSupplier(selectedSupplier);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/updateSupplier.xhtml"); //redirect to updateSupplier.xhtml
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a raw material to delete before continuing.", ""));
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void addSupplierRawMaterial(ActionEvent event) {
        try {
            List<RawMaterial> temp = selectedSupplier.getRawMaterials();
            Boolean exist = false;
            for (RawMaterial rm : temp) {
                System.out.println(rm.getId() + rawMaterial.getId());

                if (rm.getId() == rawMaterial.getId()) {
                    exist = true; //material to add already is already in the supplier's material list
                    break;
                }
            }
            System.out.println("selectedSupplier.getSupplierId(): " + selectedSupplier.getSupplierId());
            if (!exist) {
                rawMaterial = productSessionBeanLocal.getRawMaterial(getRawMaterial().getId());

                supplierSessionBeanLocal.updateSupplierRawMaterial(selectedSupplier.getSupplierId(), rawMaterial);

                selectedSupplier = supplierSessionBeanLocal.getSupplierBySupId(selectedSupplier.getSupplierId());
                selectedSupplier.setName(name);
                selectedSupplier.setContact(contact);
                selectedSupplier.setCompany(company);
                selectedSupplier.setEmail(email);
                selectedSupplier.setRanking(ranking);
                selectedSupplier.setComment(comment);
                selectedSupplier.setSupplierAddress(supplierAddress);
                selectedSupplier.setSupplierId(supplierId);

                userSessionManagerBean.setSelectedSupplier(selectedSupplier);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/updateSupplier.xhtml"); //redirect to updateProduct.xhtml
            } else { //if material to add already exists in the product's material list
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "The raw material to add already exists.", ""));
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void addASupplier(ActionEvent event) {
        try {
            Supplier temp = supplierSessionBeanLocal.getSupplierBySupId(supplierId, company);

            if (temp == null) {
                supplierAddress = new Address(street, country, city, postal, "Supplier");

                List<RawMaterial> temp2 = new ArrayList<RawMaterial>();

                supplierSessionBeanLocal.addSupplier(supplierId, name, contact, supplierAddress, ranking, comment, email, company, temp2);

                logSessionBeanLocal.addLog("Add Supplier", "Supplier Added. " + company, "addSupplier.xhtml", userSessionManagerBean.getUserId());

                ArrayList<String> al = new ArrayList<String>();
                al.add("Supplier Added");
                al.add("You have successfully added the supplier. ");
                al.add("Click on the link to return to ");
                al.add("continue");
                al.add("Web_Warehouse/searchSuppliers.xhtml");
                userSessionManagerBean.setSelectedItem(al);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/success.xhtml"); //redirect to searchSuppliers.xhtml
            } else //supplier alrdy exists
            {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "A supplier with the same supplier id OR supplier company already exists.", ""));
            }

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void updateASupplier(ActionEvent event) {
        try {
            supplierAddress = new Address(street, country, city, postal, "Supplier");

            supplierSessionBeanLocal.updateSupplier(supplierId, name, contact, supplierAddress, ranking, comment, email, company);

            logSessionBeanLocal.addLog("Update Supplier", "Supplier Information updated: " + company, "updateSupplier.xhtml", userSessionManagerBean.getUserId());

            ArrayList<String> al = new ArrayList<String>();
            al.add("Supplier Updated");
            al.add("You have successfully updated the supplier. ");
            al.add("Click on the link to return to ");
            al.add("continue");
            al.add("Web_Warehouse/searchSuppliers.xhtml");
            userSessionManagerBean.setSelectedItem(al);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://" + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort() + "/MerlionERP-war/success.xhtml");

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }

    }

    public void updateSupplier(ActionEvent event) {
        try {
            if (selectedSupplier != null) {
                userSessionManagerBean.setSelectedSupplier(selectedSupplier);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/updateSupplier.xhtml"); //redirect to updateSupplier.xhtml
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a supplier before continuing.", ""));
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void viewSupplier(ActionEvent event) {
        try {
            if (selectedSupplier != null) {
                userSessionManagerBean.setSelectedSupplier(selectedSupplier);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/viewSupplier.xhtml"); //redirect to viewSupplier.xhtml
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a supplier before continuing.", ""));
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void createRawMaterialPO(ActionEvent event) {
        try {
            if (selectedSupplier != null) {
                userSessionManagerBean.setSelectedSupplier(selectedSupplier);

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/createRawMaterialPurchaseOrder.xhtml"); //redirect to viewSupplier.xhtml
            } else {
                FacesContext.getCurrentInstance().addMessage(null,
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Please select a supplier before continuing.", ""));
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    //FOR RAW MATERIAL PURCHASE ORDER
    public void viewSuppliers(ActionEvent event) {
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + getUserSessionManagerBean().getServerName() + ":"
                    + getUserSessionManagerBean().getServerPort()
                    + "/MerlionERP-war/Web_Warehouse/searchSuppliersRMPO.xhtml"); //redirect to viewSupplier.xhtml

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void back(ActionEvent event) {
        try {
            if (event.getComponent().getId().equals("btnBackFromUpdateSupplier")) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/searchSuppliers.xhtml"); //redirect to searchSuppliers.xhtml
            } else if (event.getComponent().getId().equals("btnBackFromViewSupplier")) {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + getUserSessionManagerBean().getServerName() + ":"
                        + getUserSessionManagerBean().getServerPort()
                        + "/MerlionERP-war/Web_Warehouse/searchSuppliers.xhtml"); //redirect to searchSuppliers.xhtml
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
            // ex.printStackTrace();
        }
    }
    // <editor-fold defaultstate="collapsed" desc="Getter and Setter. Click on the + sign on the left to edit the code.">  

    /**
     * @return the supplierSessionBeanLocal
     */
    public SupplierSessionBeanLocal getSupplierSessionBeanLocal() {
        return supplierSessionBeanLocal;
    }

    /**
     * @param supplierSessionBeanLocal the supplierSessionBeanLocal to set
     */
    public void setSupplierSessionBeanLocal(SupplierSessionBeanLocal supplierSessionBeanLocal) {
        this.supplierSessionBeanLocal = supplierSessionBeanLocal;
    }

    /**
     * @return the userSessionManagerBean
     */
    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    /**
     * @param userSessionManagerBean the userSessionManagerBean to set
     */
    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    /**
     * @return the supplierId
     */
    public String getSupplierId() {
        return supplierId;
    }

    /**
     * @param supplierId the supplierId to set
     */
    public void setSupplierId(String supplierId) {
        this.supplierId = supplierId;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the contact
     */
    public Integer getContact() {
        return contact;
    }

    /**
     * @param contact the contact to set
     */
    public void setContact(Integer contact) {
        this.contact = contact;
    }

    /**
     * @return the supplierAddress
     */
    public Address getSupplierAddress() {
        return supplierAddress;
    }

    /**
     * @param supplierAddress the supplierAddress to set
     */
    public void setSupplierAddress(Address supplierAddress) {
        this.supplierAddress = supplierAddress;
    }

    /**
     * @return the street
     */
    public String getStreet() {
        return street;
    }

    /**
     * @param street the street to set
     */
    public void setStreet(String street) {
        this.street = street;
    }

    /**
     * @return the country
     */
    public String getCountry() {
        return country;
    }

    /**
     * @param country the country to set
     */
    public void setCountry(String country) {
        this.country = country;
    }

    /**
     * @return the city
     */
    public String getCity() {
        return city;
    }

    /**
     * @param city the city to set
     */
    public void setCity(String city) {
        this.city = city;
    }

    /**
     * @return the postal
     */
    public Integer getPostal() {
        return postal;
    }

    /**
     * @param postal the postal to set
     */
    public void setPostal(Integer postal) {
        this.postal = postal;
    }

    /**
     * @return the ranking
     */
    public String getRanking() {
        return ranking;
    }

    /**
     * @param ranking the ranking to set
     */
    public void setRanking(String ranking) {
        this.ranking = ranking;
    }

    /**
     * @return the comment
     */
    public String getComment() {
        return comment;
    }

    /**
     * @param comment the comment to set
     */
    public void setComment(String comment) {
        this.comment = comment;
    }

    /**
     * @return the rawMaterialsList
     */
    public List<RawMaterial> getRawMaterials() {
        return getRawMaterialsList();
    }

    /**
     * @param rawMaterialsList the rawMaterialsList to set
     */
    public void setRawMaterials(List<RawMaterial> rawMaterials) {
        this.setRawMaterialsList(rawMaterials);
    }

    /**
     * @return the email
     */
    public String getEmail() {
        return email;
    }

    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * @return the company
     */
    public String getCompany() {
        return company;
    }

    /**
     * @param company the company to set
     */
    public void setCompany(String company) {
        this.company = company;
    }

    /**
     * @return the loadAddSupplier
     */
    public String getLoadAddSupplier() {
        return loadAddSupplier;
    }

    /**
     * @param loadAddSupplier the loadAddSupplier to set
     */
    public void setLoadAddSupplier(String loadAddSupplier) {
        this.loadAddSupplier = loadAddSupplier;
    }

    /**
     * @return the loadManageSuppliers
     */
    public String getLoadManageSuppliers() {
        suppliers = supplierSessionBeanLocal.getSuppliers();

        return null;


    }

    /**
     * @param loadManageSuppliers the loadManageSuppliers to set
     */
    public void setLoadManageSuppliers(String loadManageSuppliers) {
        this.loadManageSuppliers = loadManageSuppliers;
    }

    /**
     * @return the suppliers
     */
    public List<Supplier> getSuppliers() {
        return suppliers;
    }

    /**
     * @param suppliers the suppliers to set
     */
    public void setSuppliers(List<Supplier> suppliers) {
        this.suppliers = suppliers;
    }

    /**
     * @return the loadUpdateSupplier
     */
    public String getLoadUpdateSupplier() {

        selectedSupplier = userSessionManagerBean.getSelectedSupplier();
        supplierId = selectedSupplier.getSupplierId();
        name = selectedSupplier.getName();
        company = selectedSupplier.getCompany();
        contact = selectedSupplier.getContact();
        ranking = selectedSupplier.getRanking();
        email = selectedSupplier.getEmail();
        comment = selectedSupplier.getComment();
        supplierAddress = selectedSupplier.getSupplierAddress();
        city = supplierAddress.getCity();
        country = supplierAddress.getCountry();
        postal = supplierAddress.getPostal();
        street = supplierAddress.getStreet();

        setRawMaterialsSelling(selectedSupplier.getRawMaterials());
        rawMaterialsList = productSessionBeanLocal.getRawMaterials(); //Standard List of Raw Materials


        return null;
    }

    /**
     * @param loadUpdateSupplier the loadUpdateSupplier to set
     */
    public void setLoadUpdateSupplier(String loadUpdateSuppler) {
        this.loadUpdateSupplier = loadUpdateSuppler;
    }

    /**
     * @return the selectedSupplier
     */
    public Supplier getSelectedSupplier() {
        return selectedSupplier;
    }

    /**
     * @param selectedSupplier the selectedSupplier to set
     */
    public void setSelectedSupplier(Supplier selectedSupplier) {
        this.selectedSupplier = selectedSupplier;
    }

    /**
     * @return the selectedSellingRawMaterial
     */
    public RawMaterial getSelectedSellingRawMaterial() {
        return selectedSellingRawMaterial;
    }

    /**
     * @param selectedSellingRawMaterial the selectedSellingRawMaterial to set
     */
    public void setSelectedSellingRawMaterial(RawMaterial selectedSellingRawMaterial) {
        this.selectedSellingRawMaterial = selectedSellingRawMaterial;
    }

    /**
     * @return the rawMaterial
     */
    public RawMaterial getRawMaterial() {
        return rawMaterial;
    }

    /**
     * @param rawMaterial the rawMaterial to set
     */
    public void setRawMaterial(RawMaterial rawMaterial) {
        this.rawMaterial = rawMaterial;
    }

    /**
     * @return the rawMaterialsList
     */
    public List<RawMaterial> getRawMaterialsList() {
        return rawMaterialsList;
    }

    /**
     * @param rawMaterialsList the rawMaterialsList to set
     */
    public void setRawMaterialsList(List<RawMaterial> rawMaterialsList) {
        this.rawMaterialsList = rawMaterialsList;
    }

    /**
     * @return the rawMaterialsSelling
     */
    public List<RawMaterial> getRawMaterialsSelling() {
        return rawMaterialsSelling;
    }

    /**
     * @param rawMaterialsSelling the rawMaterialsSelling to set
     */
    public void setRawMaterialsSelling(List<RawMaterial> rawMaterialsSelling) {
        this.rawMaterialsSelling = rawMaterialsSelling;
    }
    //</editor-fold>
}
